# -*- coding: iso-8859-15 -*-

#    SuperClipboard is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

from Crypto.Cipher import AES
from hashlib import md5
import base64
import cPickle
import socket
import struct

class Code:
    def encode(password,string):
        BLOCK_SIZE = 32
        PADDING = '#'
        pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
        EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
        secret = md5(password).hexdigest()
        cipher = AES.new(secret)
        encoded = EncodeAES(cipher, string)
        return encoded
    encode = staticmethod(encode)
    
    def decode(password,encodedstring):
        try:
            PADDING = '#'
            secret = md5(password).hexdigest()
            cipher = AES.new(secret)
            return  cipher.decrypt(base64.b64decode(encodedstring).rstrip(PADDING))
        except:
            return False
    decode = staticmethod(decode)

class Communication:
    def send(channel, *args):
        marshall = cPickle.dumps
        buf = marshall(args)
        value = socket.htonl(len(buf))
        size = struct.pack("L",value)
        channel.send(size)
        channel.send(buf)
    send = staticmethod(send)
    
    def receive(channel):
        unmarshall = cPickle.loads
        size = struct.calcsize("L")
        size = channel.recv(size)
        size = socket.ntohl(struct.unpack("L", size)[0])
        
        buf = ""
    
        while len(buf) < size:
            buf = channel.recv(size - len(buf))
    
        return unmarshall(buf)[0]
    receive = staticmethod(receive)

class FormatData(object):
    def Key2Balise(key):
        return ("<"+key+">","</"+key+">")
    Key2Balise = staticmethod(Key2Balise)
    
    def Str2Data(key,str=""):
        return "<"+key+">"+str+"</"+key+">"
    Str2Data = staticmethod(Str2Data)
    
    def Data2Str(key,data):
        startbalise , stopbalise = FormatData.Key2Balise(key)
        try:
            ret = data[data.index(startbalise)+len(startbalise):data.rindex(stopbalise)]
        except:
            ret = None
        return ret
    Data2Str = staticmethod(Data2Str)